// OSS上传jQuery插件
(function($) {
    // 默认配置
    const defaults = {
        stsUrl: '/oss/getStsToken',
        maxFileSize: 5 * 1024 * 1024 * 1024, // 5GB
        showProgress: true,
        showDebug: false,
        autoUpload: false,
        onProgress: null,
        onSuccess: null,
        onError: null,
        onFileSelect: null,
        // 新增：结果处理相关配置
        showResult: true,
        resultContainer: null,
        onResult: null
    };

    // 上传类
    class OSSUploader {
        constructor(element, options) {
            this.$element = $(element);
            this.options = $.extend({}, defaults, options);
            this.ossClient = null;
            this.isInitialized = false;
            this.currentFile = null;
            this.uploadResult = null;

            this.init();
        }

        init() {
            this.bindEvents();
            if (this.options.autoUpload) {
                this.preInitOSS();
            }
        }

        bindEvents() {
            const self = this;

            // 文件选择事件
            this.$element.on('change', function(e) {
                const files = this.files;
                if (files && files.length > 0) {
                    self.handleFileSelect(files[0]);
                }
            });

            // 拖拽事件
            // if (this.options.dropArea) {
            //     this.setupDropArea(this.options.dropArea);
            // }
        }

        // setupDropArea(dropArea) {
        //     const self = this;
        //     const $dropArea = $(dropArea);
        //
        //     $dropArea.on('dragover', function(e) {
        //         e.preventDefault();
        //         $dropArea.addClass('highlight');
        //     });
        //
        //     $dropArea.on('dragleave', function(e) {
        //         e.preventDefault();
        //         $dropArea.removeClass('highlight');
        //     });
        //
        //     $dropArea.on('drop', function(e) {
        //         e.preventDefault();
        //         $dropArea.removeClass('highlight');
        //
        //         const files = e.originalEvent.dataTransfer.files;
        //         if (files.length > 0) {
        //             self.$element.prop('files', files);
        //             self.handleFileSelect(files[0]);
        //         }
        //     });
        //
        //     $dropArea.on('click', function() {
        //         self.$element.click();
        //     });
        // }

        handleFileSelect(file) {
            this.currentFile = file;

            // 检查文件大小
            if (file.size > this.options.maxFileSize) {
                this.showMessage(`文件大小超过 ${this.options.maxFileSize / 1024 / 1024 / 1024}GB 限制`, 'error');
                return;
            }

            // 触发文件选择回调
            if (typeof this.options.onFileSelect === 'function') {
                this.options.onFileSelect(file);
            }

            // 自动上传
            if (this.options.autoUpload) {
                this.upload();
            }
        }

        async preInitOSS() {
            try {
                await this.initOSSClient();
            } catch (error) {
                console.log('预初始化失败，将在上传时重新初始化');
            }
        }

        async initOSSClient() {
            return new Promise((resolve, reject) => {
                $.ajax({
                    url: this.options.stsUrl,
                    type: 'GET',
                    dataType: 'json',
                    timeout: 10000,
                    success: (response) => {
                        if (response.code === 0) {
                            try {
                                const stsData = response.data;

                                this.ossClient = new OSS({
                                    region: stsData.region || "oss-cn-beijing",
                                    accessKeyId: stsData.accessKeyId,
                                    accessKeySecret: stsData.accessKeySecret,
                                    stsToken: stsData.securityToken,
                                    bucket: stsData.bucket || "xjksii81ks",
                                    secure: true,
                                    timeout: 60000,
                                });

                                this.isInitialized = true;
                                this.showMessage('OSS客户端初始化成功', 'success');
                                resolve(this.ossClient);
                            } catch (error) {
                                this.showMessage('初始化失败: ' + error.message, 'error');
                                reject(error);
                            }
                        } else {
                            const errorMsg = response.msg || '获取STS Token失败';
                            this.showMessage(errorMsg, 'error');
                            reject(new Error(errorMsg));
                        }
                    },
                    error: (xhr, status, error) => {
                        const errorMsg = '请求失败: ' + (error || status || '网络错误');
                        this.showMessage(errorMsg, 'error');
                        reject(new Error(errorMsg));
                    }
                });
            });
        }

        generateFileName(originalName) {
            const timestamp = new Date().getTime();
            const random = Math.random().toString(36).substring(2, 8);
            const extension = originalName.split('.').pop();
            return `uploads/${timestamp}_${random}.${extension}`;
        }

        updateProgress(percentage) {
            if (this.options.showProgress && this.options.progressContainer) {
                const progress = Math.round(percentage * 100);
                $(this.options.progressBar).css('width', `${progress}%`);
                $(this.options.progressText).text(`${progress}%`);
                $(this.options.progressContainer).show();
            }

            if (typeof this.options.onProgress === 'function') {
                this.options.onProgress(percentage);
            }
        }

        showMessage(message, type = 'info') {
            if (this.options.messageContainer) {
                const messageEl = $(this.options.messageContainer);
                messageEl.removeClass('info success error warning').addClass(type).text(message).show();
            }
        }

        // 处理上传结果
        handleUploadResult(result, fileName, file) {
            // 构建详细的上传结果信息
            const uploadInfo = {
                // 文件基本信息
                originalName: file.name,
                fileName: fileName,
                fileSize: file.size,
                fileType: file.type,
                uploadTime: new Date().toLocaleString(),

                // OSS返回信息
                url: result.url,
                name: result.name,
                etag: result.etag,
                requestId: result.requestId,
                res: result.res,

                // 其他有用信息
                bucket: this.ossClient?.options.bucket,
                region: this.ossClient?.options.region,

                // 格式化显示信息
                displayInfo: {
                    fileSizeFormatted: this.formatFileSize(file.size),
                    uploadTimeFormatted: new Date().toLocaleString('zh-CN'),
                    fullUrl: result.url
                }
            };

            this.uploadResult = uploadInfo;

            // 显示结果
            if (this.options.showResult && this.options.resultContainer) {
                this.displayResult(uploadInfo);
            }

            // 触发结果回调
            if (typeof this.options.onResult === 'function') {
                this.options.onResult(uploadInfo);
            }

            return uploadInfo;
        }

        // 格式化文件大小
        formatFileSize(bytes) {
            if (bytes === 0) return '0 B';
            const k = 1024;
            const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }

        // 显示上传结果
        displayResult(uploadInfo) {
            const container = $(this.options.resultContainer);
            if (container.length) {
                container.show();

                // 更新各个结果字段
                $('#resultFileName').text(uploadInfo.fileName);
                $('#resultFileUrl').text(uploadInfo.url);
                $('#resultFileSize').text(uploadInfo.displayInfo.fileSizeFormatted);
                $('#resultUploadTime').text(uploadInfo.displayInfo.uploadTimeFormatted);
                $('#resultETag').text(uploadInfo.etag || '-');
                $('#resultRequestId').text(uploadInfo.requestId || '-');
            }
        }

        async upload(file = null) {
            if (file) {
                this.currentFile = file;
            }

            if (!this.currentFile) {
                this.showMessage('请先选择文件', 'warning');
                return Promise.reject(new Error('没有选择文件'));
            }

            try {
                if (!this.ossClient || !this.isInitialized) {
                    this.showMessage('正在初始化OSS客户端...', 'info');
                    await this.initOSSClient();
                }

                const fileName = this.generateFileName(this.currentFile.name);
                this.showMessage(`开始上传文件: ${fileName}`, 'info');

                let result;
                const uploadOptions = {
                    progress: (p) => {
                        this.updateProgress(p);
                    },
                    headers: {
                        "Cache-Control": "no-cache",
                        "x-oss-forbid-overwrite": "false",
                    }
                };

                // 根据文件大小选择上传方式
                if (this.currentFile.size < 10 * 1024 * 1024) {
                    result = await this.ossClient.put(fileName, this.currentFile, uploadOptions);
                } else {
                    result = await this.ossClient.multipartUpload(fileName, this.currentFile, {
                        ...uploadOptions,
                        parallel: 4,
                        partSize: 1024 * 1024
                    });
                }

                // 处理上传结果
                const uploadInfo = this.handleUploadResult(result, fileName, this.currentFile);

                this.showMessage(`文件上传成功! 文件名: ${fileName}`, 'success');

                if (typeof this.options.onSuccess === 'function') {
                    this.options.onSuccess(result, fileName, uploadInfo);
                }

                return uploadInfo;

            } catch (error) {
                console.error('上传失败:', error);

                let errorMessage = '上传失败: ' + error.message;
                if (error.name === 'RequestError') {
                    errorMessage = '网络连接错误，请检查网络连接或稍后重试';
                }

                this.showMessage(errorMessage, 'error');

                if (typeof this.options.onError === 'function') {
                    this.options.onError(error);
                }

                throw error;
            }
        }

        // 公共方法
        setFile(file) {
            this.currentFile = file;
        }

        getFile() {
            return this.currentFile;
        }

        getResult() {
            return this.uploadResult;
        }

        reset() {
            this.$element.val('');
            this.currentFile = null;
            this.uploadResult = null;

            if (this.options.progressContainer) {
                $(this.options.progressContainer).hide();
                $(this.options.progressBar).css('width', '0%');
                $(this.options.progressText).text('0%');
            }

            if (this.options.resultContainer) {
                $(this.options.resultContainer).hide();
            }

            if (this.options.messageContainer) {
                $(this.options.messageContainer).hide();
            }
        }

        // 获取上传历史
        getUploadHistory() {
            return JSON.parse(localStorage.getItem('ossUploadHistory') || '[]');
        }

        // 保存上传记录到本地存储
        saveToHistory(uploadInfo) {
            const history = this.getUploadHistory();
            history.unshift({
                ...uploadInfo,
                timestamp: new Date().getTime()
            });

            // 只保留最近10条记录
            const limitedHistory = history.slice(0, 10);
            localStorage.setItem('ossUploadHistory', JSON.stringify(limitedHistory));
        }
    }

    // jQuery插件定义
    $.fn.ossUpload = function(options) {
        return this.each(function() {
            if (!$.data(this, 'ossUploader')) {
                $.data(this, 'ossUploader', new OSSUploader(this, options));
            }
        });
    };

    // 获取实例
    $.fn.getOSSUploader = function() {
        return $.data(this[0], 'ossUploader');
    };

})(jQuery);